export const dateTypeOptions = [
  { label: '固定日期', value: 1 },
  { label: '自定义', value: 0 },
];

export const viewTypeOptions = [
  { label: '年度视图', value: 0 },
  { label: '季度视图', value: 1 },
  { label: '月度视图', value: 2 },
];

export const typeOptions = [
  { label: '24', value: '24' },
  { label: '96', value: '96' },
];

// 映射
const SERIES_MAP = {
  realtimePrice: { name: '实时均价', type: 'line', color: '#E86452' },
  recentlyPrice: { name: '日前均价', type: 'dashed', color: '#5E92F6' },
  realtime: { name: '实时', type: 'line', color: '#E86452' },
  '330kV河上双回线': { type: 'dashed', color: '#2174FF' },
  '330kV八玉一线': { type: 'dashed', color: '#3CB1FB' },
  '750kV河武双回线、沙鱼双回线、河白线': { type: 'dashed', color: '#07A872' },
  '750kV沙鱼双回线、敦高三回西线': { type: 'dashed', color: '#D29E08' },
  '750kV沙鱼双回线、高泉三回西线': { type: 'dashed', color: '#ED8139' },
  祁韶近区风电总加: { type: 'dashed', color: '#FB6E77' },
  '330kV玉门#1、#2主变': { type: 'dashed', color: '#FF70CF' },
  '750kV河白一线、750kV武白双回、750kV宁官双回': { type: 'dashed', color: '#B382F0' },
  '750kV河泉双回线、沙鱼双回线、甘泉I线、甘河I线': { type: 'dashed', color: '#575FA1' },
  '330kV高布双回': { type: 'dashed', color: '#075288' },
  '330kV山上双回线': { type: 'dashed', color: '#994B42' },
  '750kV武白双回、750kV河白双回、750kV官东双回': { type: 'dashed', color: '#E86452' },
  '110kV萧甜双回线': { type: 'dashed', color: '#A8C9F9' },
  '750kV河武双回线、沙鱼双回线': { type: 'dashed', color: '#07A872' },
  '750kV高泉双回线、沙鱼双回线': { type: 'dashed', color: '#D29E08' },
  '750kV敦高双回线、沙鱼双回线': { type: 'dashed', color: '#ED8139' },
  '750kV泉河双回线、沙鱼双回线': { type: 'dashed', color: '#FB6E77' },
  '甘肃-青海日前': { type: 'dashed', color: '#2174FF' },
  '甘肃-陕西日前': { type: 'dashed', color: '#3CB1FB' },
  '甘肃-湖南日前': { type: 'dashed', color: '#07A872' },
  '甘肃-宁夏日前': { type: 'dashed', color: '#D29E08' },
  合计日前: { type: 'dashed', color: '#ED8139' },
  '甘肃-新疆日前': { type: 'dashed', color: '#FB6E77' },

  光伏实时出力: { type: 'line', color: '#2174FF' },
  新能源实时出力: { type: 'line', color: '#3CB1FB' },
  水电实时出力: { type: 'line', color: '#07A872' },
  风机实时出力: { type: 'line', color: '#D29E08' },
  非市场化机组实际出力: { type: 'line', color: '#ED8139' },

  河东日前: { type: 'line', color: '#2174FF' },
  河东null: { type: 'line', color: '#3CB1FB' },
  河西日前: { type: 'line', color: '#07A872' },
  河西null: { type: 'line', color: '#D29E08' },
};

export const MODS = [
  {
    datakey: 'spotPrice',
    name: '现货价格',
    unit: '单位：元/MWh',
    dimensions: ['realtimePrice', 'recentlyPrice'],
    export: true,
  },
  {
    datakey: 'provinceLoadLinkNewEnergy',
    name: '省内负荷&联络线-新能源',
    unit: '单位：MW',
    dimensions: ['realtime'],
  },
  {
    datakey: 'provinceLoadLink',
    name: '省内负荷&联络线',
    unit: '单位：MW',
    dimensions: ['realtime'],
  },
  {
    datakey: 'newEnergy',
    name: '新能源',
    unit: '单位：MW',
    dimensions: ['realtime'],
    export: true,
  },
  {
    datakey: 'provinceLoad',
    name: '省内负荷',
    unit: '单位：MW',
    dimensions: ['realtime'],
    export: true,
  },
  {
    datakey: 'link',
    name: '联络线',
    unit: '单位：MW',
    dimensions: ['realtime'],
    export: true,
  },
];
export const GS_MODS = (_data) => {
  const map = {};
  Object.entries(_data).forEach((t) => {
    map[t[0]] = Object.keys(t[1]);
  });
  return [
    {
      datakey: 'zoneElectricityPrice',
      name: '分区电价',
      unit: '单位元/MWh',
      dimensions: map['zoneElectricityPrice'],
      export: true,
    },
    {
      datakey: 'spotInformationTieLine',
      name: '日前系统间联络线总输电曲线预测',
      unit: '单位：MW',
      dimensions: map['spotInformationTieLine'],
      export: true,
    },
    {
      datakey: 'releaseSectionPowerForecast',
      name: '关键断面输电能力预测',
      unit: '单位：MW',
      dimensions: map['releaseSectionPowerForecast'],
      export: true,
    },
    {
      datakey: 'operationRealtimePowerFlow',
      name: '重要通道实际输电情况',
      unit: '单位：MW',
      dimensions: map['operationRealtimePowerFlow'],
      export: true,
    },
    {
      datakey: 'realTimeOutputOfTheUnit',
      name: '机组实时出力情况',
      unit: '单位：MW',
      dimensions: map['realTimeOutputOfTheUnit'],
      export: true,
    },
  ];
};
// 数据处理
const timeKey = '_time';

function fmtJson(_data, _keys) {
  if (!_data || !_keys.length) return {};
  let temp = {};
  for (const skey in _data) {
    // skey 系列键
    const listMap = _data[skey];
    if (listMap?.length) {
      // 一层
      listMap.map(({ xAxis, value }) => {
        if (!temp[xAxis]) {
          temp[xAxis] = { [timeKey]: xAxis };
        }
        temp[xAxis][skey] = value;
      });
    } else {
      // 两层
      for (const k1 in listMap) {
        listMap[k1].map(({ xAxis, value }) => {
          const id = `${k1}_${xAxis}`;
          if (!temp[id]) {
            temp[id] = { [timeKey]: xAxis };
          }
          temp[id][skey] = value;
        });
      }
    }
  }
  const sortedKeys = Object.keys(temp).sort();
  return sortedKeys.map((key) => temp[key]);
}

// 图表配置
export const getChartOption = (_data, _info, _provinceId = undefined, passageName = '') => {
  let __info = JSON.parse(JSON.stringify(_info));
  let __data = _data;
  // 重要通道实际输电情况
  if (_provinceId === '62' && _info.datakey === 'operationRealtimePowerFlow') {
    __data = {
      [passageName]: _data[passageName],
    };
    __info.dimensions = __info.dimensions.filter((i) => i === passageName);
  }
  if (!__data || !__info) return null;
  const sKeys = __info?.dimensions || [];
  const series = sKeys.map((k) => {
    if (_provinceId === '62') {
      const t = SERIES_MAP[k];
      return {
        name: k,
        ...t,
        type: t?.type || 'line',
      };
    }
    return SERIES_MAP[k];
  });

  const jsonList = fmtJson(__data, sKeys);
  const dataset = {
    source: jsonList,
    dimensions: [timeKey, ...sKeys],
  };

  return {
    series,
    dataset,
    grid: { top: 12, left: 48, bottom: 72, right: 10 },
    tooltip: {},
    legend: {},
    xAxis: [{ type: 'category' }],
    yAxis: [{ type: 'value' }],
    dataZoomSlider: true,
  };
};
// 导出数据
export const exportHelpr = (_datas, { subTitle, stationName, provinceId }) => {
  let list = [];
  (provinceId ? GS_MODS(_datas) : MODS).map((x) => {
    if (x.export) {
      let itemName = '';
      if (x.datakey === 'spotPrice') {
        itemName = stationName;
      }
      itemName += `${x.name} ${subTitle} ${x.unit}`;
      const jsonList = fmtJson(_datas?.[x.datakey], x.dimensions);
      const itemData = [
        ...[timeKey, ...x.dimensions].map((k, i) => {
          const sname = (provinceId && i > 0 ? k : SERIES_MAP?.[k]?.name) || '日期';
          return [sname, ...jsonList.map((item) => item[k])];
        }),
      ];
      list.push({
        data: itemData,
        header: [itemName, ...jsonList.map(() => '')],
        sheetName: x.name,
      });
    }
  });
  return list;
};

// 便于扩展
const TIME_KEY = 'time';
const POINTS = [
  { code: 'pointData1', name: 'D日' },
  { code: 'pointData2', name: 'D-1日' },
  { code: 'pointData3', name: 'D-2日' },
];
const POINT_COL = {
  code: TIME_KEY,
  name: '点位',
  getCellProps: (v) => {
    if (v?.length === 4) {
      return { style: { color: '#A7A8A9' } };
    }
  },
};

const DATA_MAP = {
  loadForecast: { name: '负荷预测', type: 'dashed', color: '#FD4F43' },
  eastPlanPowerForecast: { name: '东送计划预测', type: 'dashed', color: '#18A0FB' },
  nonMarketPowerForecast: { name: '非市场出力计划', type: 'dashed', color: '#18A0FB' },
  totalNewEnergyPowerForecast: { name: '全网新能源', type: 'dashed', color: '#30D485' },
  totalWindPowerForecast: { name: '全网风电', type: 'dashed', color: '#18A0FB' },
  totalPhotovoltaicPowerForecast: { name: '全网光伏', type: 'dashed', color: '#FFD60A' },
  positiveInfo: { name: '正备用', type: 'dashed', color: '#FD4F43' },
  negativeInfo: { name: '负备用', type: 'dashed', color: '#30D485' },
};

/** 渲染配置 */
const pointColumns = [
  { ...POINT_COL, width: 100 },
  ...POINTS.map((x) => ({ ...x, align: 'center' })),
];

export const myModuls = [
  {
    id: 'fhyc', // 数据标识
    name: '负荷预测',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 24,
    columns: pointColumns,
    datakeys: ['loadForecast'],
    chartType: 'timeline', // 携带时间线
  },
  {
    id: 'dsjhyc', // 数据标识
    name: '东送计划预测',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 24,
    columns: pointColumns,
    datakeys: ['eastPlanPowerForecast'],
    chartType: 'timeline', // 携带时间线
  },
  {
    id: 'fsccljh', // 数据标识
    name: '非市场出力计划',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 24,
    columns: pointColumns,
    datakeys: ['nonMarketPowerForecast'],
    chartType: 'timeline', // 携带时间线
  },
  {
    id: 'xnyclyc', // 数据标识
    name: '新能源出力预测',
    unit: '单位：MW',
    group: 'groupMx', // 图联动
    span: 24,
    columns: [
      POINT_COL,
      { code: 'totalNewEnergyPowerForecast', name: '全网新能源', align: 'center' },
      { code: 'totalWindPowerForecast', name: '全网风电', align: 'center' },
      { code: 'totalPhotovoltaicPowerForecast', name: '全网光伏', align: 'center' },
    ],
    datakeys: [
      'totalNewEnergyPowerForecast',
      'totalWindPowerForecast',
      'totalPhotovoltaicPowerForecast',
    ],
    chartType: 'timeline', // 携带时间线
    select: POINTS[0].code,
    selectOption: POINTS.map((item, i) => ({
      value: item.code,
      label: i === 0 ? item.name : item.name + '预测',
    })),
  },
  {
    id: 'byxx', // 数据标识
    name: '备用信息',
    unit: '单位：MW',
    span: 24,
    columns: [
      POINT_COL,
      { code: 'positiveInfo', name: '正备用', align: 'center' },
      { code: 'negativeInfo', name: '负备用', align: 'center' },
    ],
    datakeys: ['positiveInfo', 'negativeInfo'],
  },
];

const chartBase = {
  dataset: { dimensions: [], source: [] },
  grid: { top: 12, left: 48, bottom: 75, right: 75 },
  legend: {},
  tooltip: {},
  dataZoomSlider: true,
  xAxis: [{ type: 'category', formatter: (v) => v }],
  yAxis: [{ type: 'value' }],
  series: [],
};

/** 蒙西长周期看板数据处理 */
export const handleRenderData = (_dataSource) => {
  const fmtDatesMap = ({ data, json, key }) => {
    // 按时间维度 => Json对象
    let result = { ...json };
    const pointList = data || []; // 点位数据
    let sum = 0; // 单日总和
    pointList.map(({ xAxis, value }) => {
      const val = +value || 0;
      const id = xAxis;
      sum += val;
      if (!result.data[id]) {
        result.data[id] = { id, xAxis, [TIME_KEY]: xAxis };
      }
      result.data[id][key] = _.round(val, 2).toFixed(2); // 点位值 统一保留两位
    });
    return result;
  };
  const result = _.cloneDeep(myModuls);
  if (!_dataSource) return result;
  return result.map((item) => {
    let tableData; // 表格数据
    let chartOption = _.cloneDeep(chartBase); // 图表配置
    const { datakeys = [] } = item;
    const len = datakeys?.length;
    chartOption.series = datakeys.map((key) => DATA_MAP[key]);
    if (item.chartType === 'timeline') {
      // 时间线图，含预测维度
      chartOption.timeline = { title: '预测版本', data: POINTS.map((x) => x.name) };
      if (len > 1) {
        // 长度大于1时，表格列=图系列
        tableData = {}; // 有切换操作，映射存object
        let timelineOptions = [];
        const dimensions = ['id', ...datakeys];
        POINTS.map((point) => {
          const pointCode = point.code;
          let json = { data: {}, avg: {} };
          for (const key of datakeys) {
            json = fmtDatesMap({ key, json, data: _dataSource?.[key]?.[pointCode] || {} });
          }
          const chartData = Object.values(json.data);
          chartData.sort((a, b) => Number(a.id) - Number(b.id));
          timelineOptions.push({ dataset: { dimensions, source: chartData } });
          let pointTableData = [];
          for (const date in _.groupBy(chartData, 'date')) {
            pointTableData.push({
              ...json.avg[date],
              children: chartData,
            });
          }
          tableData[pointCode] = pointTableData;
        });
        chartOption.timeline.options = timelineOptions;
      } else {
        // 系列长度为1时，表格列=预测维度
        tableData = [];
        let json = { data: {}, avg: {} };
        POINTS.map((point) => {
          const pointCode = point.code;
          const _data = _dataSource?.[datakeys[0]]?.[pointCode] || {};
          json = fmtDatesMap({ key: pointCode, json, data: _data });
        });
        const chartData = Object.values(json.data);
        chartData.sort((a, b) => Number(a.id) - Number(b.id));
        chartOption.timeline.options = POINTS.map((point) => ({
          dataset: { dimensions: ['id', point.code], source: chartData },
        }));
        tableData = chartData;
      }
    } else {
      // 2. 普通图形，表格列=图系列
      tableData = [];
      chartOption.grid.right = 10;
      let json = { data: {}, avg: {} };
      const dimensions = ['id', ...datakeys];
      for (const key of datakeys) {
        const _data = _dataSource?.[key] || {};
        json = fmtDatesMap({ key, json, data: _data });
      }
      const chartData = Object.values(json.data);
      chartData.sort((a, b) => Number(a.id) - Number(b.id));
      chartOption.dataset = { dimensions, source: chartData };
      tableData = chartData;
    }
    return {
      ...item,
      tableData, // 表格数据
      chartOption, // 图配置
    };
  });
};

// 导出数据
export const handleExportDataMengXi = (_charts, _dataSource) => {
  let result = [];
  _charts.map((item) => {
    const { datakeys = [] } = item;
    if (item.chartType === 'timeline') {
      const options = item?.chartOption?.timeline?.options;
      datakeys.map((key) => {
        const sheetName = DATA_MAP?.[key]?.name || ''; // 名称
        let temp = { name: sheetName, data: [['类型']] };
        POINTS.map((p, i) => {
          const _name = p.name;
          const _data = options?.[i]?.dataset?.source || [];
          const _values = _data.map((x) => {
            i === 0 && temp.data[0].push(x.id);
            const vkey = datakeys.length > 1 ? key : p.code;
            return x[vkey];
          });
          temp.data.push([_name, ..._values]);
        });
        result.push(temp);
      });
    } else {
      const sheetName = item.name;
      const _data = item?.chartOption?.dataset?.source;
      let temp = { name: sheetName, data: [['类型']] };
      datakeys.map((key, i) => {
        const _name = DATA_MAP?.[key]?.name || '';
        const _values = _data.map((x) => {
          i === 0 && temp.data[0].push(x.id);
          return x[key];
        });
        temp.data.push([_name, ..._values]);
      });
      result.push(temp);
    }
  });
  return result;
};
